<template>
  <div class="max-w-4xl mx-auto px-4 py-10">
    <div class="bg-white/80 backdrop-blur rounded-xl shadow-lg p-6">
      <div class="flex items-start justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">实时金价查询</h1>
          <p class="text-sm text-gray-600 mt-1">数据来源：金价接口（free.xwteam.cn）</p>
        </div>

        <div class="text-right">
          <div class="text-sm text-gray-500">自动刷新</div>
          <div class="flex items-center space-x-2 mt-1">
            <button
              @click="toggleAuto"
              :class="['px-3 py-1 rounded-md text-sm font-medium', autoRefresh ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700']"
            >
              {{ autoRefresh ? '已开启' : '已关闭' }}
            </button>
            <select v-model.number="intervalSec" class="border rounded-md text-sm px-2 py-1">
              <option :value="15">15s</option>
              <option :value="30">30s</option>
              <option :value="60">60s</option>
            </select>
          </div>
        </div>
      </div>

      <div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4 items-start">
        <div class="md:col-span-2">
          <!-- 黄金卡片 -->
          <div class="gold-card rounded-lg p-5 shadow-md mb-4">
            <div class="flex items-center justify-between">
              <div class="flex items-center space-x-4">
                <div class="gold-emoji text-4xl">🥇</div>
                <div>
                  <div class="text-sm text-gray-800">黄金（Au）</div>
                  <div class="text-4xl font-extrabold mt-1 tracking-tight text-amber-700">{{ goldPriceDisplay }}</div>
                  <div class="mt-1 text-sm text-gray-600">接口更新时间：{{ parsed?.UpTime ?? '--' }}</div>
                </div>
              </div>

              <div class="text-right">
                <div class="text-sm text-gray-500">涨跌</div>
                <div :class="['text-lg font-semibold mt-1', goldChangeClass]">{{ goldChangeDisplay }}</div>
                <div class="mt-2 text-xs text-gray-500">买/卖：{{ formatNum(goldItem?.BP) }} / {{ formatNum(goldItem?.SP) }}</div>
              </div>
            </div>

            <div class="mt-4 grid grid-cols-2 gap-2 text-sm text-gray-700">
              <div>最高：<span class="font-medium">{{ formatNum(goldItem?.High) }}</span></div>
              <div>最低：<span class="font-medium">{{ formatNum(goldItem?.Low) }}</span></div>
            </div>
          </div>

          <!-- 金价列表 -->
          <div class="bg-white rounded-lg p-4 border">
            <div class="text-sm text-gray-700 font-medium mb-2">金价列表</div>
            <!-- 如果没有可展示的表格则显示原始数据 -->
            <div v-if="!hasTables" class="mt-2 p-2 bg-gray-50 rounded text-xs text-gray-700 overflow-auto max-h-40">{{ prettyRaw }}</div>

            <div v-else class="mt-2 space-y-4">
              <div v-for="cat in categories" :key="cat.key" class="rounded">
                <div class="font-medium mb-2 text-gray-600">{{ cat.title }}（{{ cat.items.length }}）</div>
                <div class="overflow-auto rounded border">
                  <table class="min-w-full text-sm table-auto">
                    <thead class="bg-gray-50 text-left text-xs text-gray-600">
                      <tr>
                        <th class="px-3 py-2">符号</th>
                        <th class="px-3 py-2">名称</th>
                        <th class="px-3 py-2 text-right">买价</th>
                        <th class="px-3 py-2 text-right">卖价</th>
                        <th class="px-3 py-2 text-right">最高</th>
                        <th class="px-3 py-2 text-right">最低</th>
                        <th class="px-3 py-2 text-right">排序</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(it, idx) in cat.items" :key="it.Symbol" :class="[idx % 2 ? 'bg-white' : 'bg-gray-50', 'hover:bg-gray-100']">
                        <td class="px-3 py-2 font-mono">{{ it.Symbol }}</td>
                        <td class="px-3 py-2">{{ it.Name }}</td>
                        <td class="px-3 py-2 text-right">{{ formatNum(it.BP) }}</td>
                        <td class="px-3 py-2 text-right">{{ formatNum(it.SP) }}</td>
                        <td class="px-3 py-2 text-right">{{ formatNum(it.High) }}</td>
                        <td class="px-3 py-2 text-right">{{ formatNum(it.Low) }}</td>
                        <td class="px-3 py-2 text-right">{{ it.Sort ?? '-' }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg p-4 border flex flex-col space-y-3">
          <div class="flex-1">
            <div class="text-sm text-gray-500">请求状态</div>
            <div class="mt-2">
              <span v-if="loading" class="text-blue-600">加载中…</span>
              <span v-else-if="error" class="text-red-600">{{ error }}</span>
              <span v-else class="text-green-600">正常（上次请求 {{ lastFetchDiff }} 前）</span>
            </div>
          </div>

          <div class="flex items-center space-x-2">
            <button @click="fetchData" class="primary-button w-full">刷新</button>
            <button @click="copyRaw" class="border rounded px-3 py-1 text-sm">复制</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'

useHead({ title: '实时金价 - 生活工具' })

const loading = ref(false)
const error = ref('')
const raw = ref(null)
const parsed = ref(null)
const lastFetched = ref(null)

const autoRefresh = ref(true)
const intervalSec = ref(30)
let timer = null

const API_URL = 'https://free.xwteam.cn/api/gold/trade'

function safeParseData(data) {
  // 有些接口会把 data 返回为字符串（可能是 JSON 字符串或文本），尝试解析
  if (!data) return null
  if (typeof data === 'string') {
    // 尝试 JSON 解析
    try {
      return JSON.parse(data)
    } catch (e) {
      // 不是 JSON，尝试简单的数字提取
      const m = data.match(/([0-9]+\.?[0-9]*)/g)
      if (m && m.length) {
        return { rawString: data, numbers: m }
      }
      return { rawString: data }
    }
  }
  return data
}

async function fetchData() {
  loading.value = true
  error.value = ''
  try {
    const res = await fetch(API_URL, { method: 'GET' })
    const json = await res.json()
    raw.value = json
    // 接口约定：{code, msg, data}
    parsed.value = safeParseData(json.data ?? json)
    lastFetched.value = Date.now()
  } catch (e) {
    error.value = e.message || String(e)
  } finally {
    loading.value = false
  }
}

function startTimer() {
  stopTimer()
  if (!autoRefresh.value) return
  timer = setInterval(() => {
    fetchData()
  }, Math.max(1000, intervalSec.value * 1000))
}

function stopTimer() {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

function toggleAuto() {
  autoRefresh.value = !autoRefresh.value
  if (autoRefresh.value) startTimer()
  else stopTimer()
}

function pretty(obj) {
  try {
    return JSON.stringify(obj, null, 2)
  } catch (e) {
    return String(obj)
  }
}

const prettyRaw = computed(() => pretty(raw.value))

// 将接口返回的分类（LF/SH/GJ）组织为方便渲染的数组
const categories = computed(() => {
  const p = parsed.value || {}
  const map = { LF: '本地(LF)', SH: '上期所(SH)', GJ: '国际(GJ)' }
  return ['LF', 'SH', 'GJ'].map((k) => ({ key: k, title: map[k] || k, items: Array.isArray(p[k]) ? p[k] : [] }))
})

const hasTables = computed(() => categories.value.some((c) => c.items && c.items.length))

function formatNum(n) {
  if (n === 0) return '0'
  if (n == null) return '-'
  const num = Number(n)
  if (isNaN(num)) return String(n)
  return num.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 3 })
}

// 优先展示黄金(Au)的数据
const goldItem = computed(() => {
  const p = parsed.value || {}
  const lists = [].concat(Array.isArray(p.LF) ? p.LF : [], Array.isArray(p.SH) ? p.SH : [], Array.isArray(p.GJ) ? p.GJ : [])
  // 优先按 Symbol 精确匹配 'Au'，否则按名称中含“黄金”或 Symbol 包含 'Au' 的顺序匹配
  let found = lists.find((i) => i && (i.Symbol === 'Au' || i.Symbol === 'AU' || i.Symbol === 'Au9999'))
  if (!found) found = lists.find((i) => i && /黄金|Au/i.test(i.Name || i.Symbol || ''))
  if (!found) return null
  return found
})

const goldPriceDisplay = computed(() => {
  const g = goldItem.value
  if (!g) return displayPriceFallback()
  // 以 SP（卖价）为准显示最新价，若无则显示 BP
  const v = g.SP ?? g.BP ?? null
  if (v == null) return displayPriceFallback()
  return formatNum(v)
})

function displayPriceFallback() {
  const p = parsed.value
  if (!p) return '--'
  return p.price ?? p.now ?? p.最新价 ?? p.新价 ?? p.last ?? (p.n || (p.numbers && p.numbers[0])) ?? '--'
}

const goldChange = computed(() => {
  const g = goldItem.value
  if (!g) return null
  const bp = Number(g.BP)
  const sp = Number(g.SP)
  if (!isNaN(bp) && !isNaN(sp)) {
    const diff = sp - bp
    const pct = bp ? (diff / bp) * 100 : 0
    return { diff, pct }
  }
  return null
})

const goldChangeDisplay = computed(() => {
  const c = goldChange.value
  if (!c) return displayChangeFallback()
  const sign = c.diff > 0 ? '+' : c.diff < 0 ? '' : ''
  return `${sign}${formatNum(c.diff)} (${sign}${Math.abs(c.pct).toFixed(2)}%)`
})

function displayChangeFallback() {
  const p = parsed.value
  if (!p) return '--'
  return p.change ?? p.涨跌 ?? p.changeRate ?? (p.numbers && p.numbers[1]) ?? '--'
}

const goldChangeClass = computed(() => {
  const c = goldChange.value
  if (!c) return 'text-gray-700'
  return c.diff > 0 ? 'text-red-600' : c.diff < 0 ? 'text-green-600' : 'text-gray-700'
})

const lastUpdatedDisplay = computed(() => {
  if (!lastFetched.value) return '—'
  const d = new Date(lastFetched.value)
  return d.toLocaleString()
})

const lastFetchDiff = computed(() => {
  if (!lastFetched.value) return '—'
  const s = Math.floor((Date.now() - lastFetched.value) / 1000)
  if (s < 60) return `${s}s`
  return `${Math.floor(s / 60)}m`
})

function copyRaw() {
  const text = pretty(raw.value)
  navigator.clipboard?.writeText(text)
}

onMounted(() => {
  fetchData()
  startTimer()
})

onBeforeUnmount(() => {
  stopTimer()
})
</script>

<style scoped>
.primary-button{
  background: linear-gradient(90deg,#4f46e5,#06b6d4);
  color: white;
  padding: 0.5rem 0.75rem;
  border-radius: 0.375rem;
  font-weight: 600;
}

.gold-card{
  background: linear-gradient(180deg, rgba(255,247,224,0.9), rgba(255,241,204,0.9));
  border: 1px solid rgba(245,158,11,0.12);
}
.gold-emoji{ filter: drop-shadow(0 4px 8px rgba(0,0,0,0.06)); }

/* 表格视觉改进 */
table th{ font-weight:600 }
table td, table th { border-bottom: 0 }

</style>
